import axios from 'axios'
import router from '../router'
import {Message} from 'element-ui';
import cryptoJs from 'crypto-js'

const baseURL = 'api'

export default {
    get,
    post,
    put,
    del,
    baseURL,
    login,
}


const service = axios.create({ // 创建服务
    baseURL: baseURL,
    timeout: 100000,// 请求延时
    validateStatus: function (status) {
        return true; // default
    },
})

/**
 * 登录请求
 */
function login(params) {
    params.password = encryptAES(params.password, 'C64EC4C5AEBDEC29FB2B3628C7FBA57E')
    // params.password = decryptAES(params.password, 'c64ec4c5aebdec29fb2b3628c7fba57e');
    let config = {
        baseURL: baseURL,
        method: 'post',
        url: '/small-service-auth/oauth/token',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Basic d2ViLXBjOndlYi1wYy1zdGFydA==',
        },
        params
    };
    return new Promise((resolve, reject) => {
        axios(config).then(res => {
            if (res.status !== 200) {
                Message.error("登录错误")
                reject(res.data)
            } else if (res.status === 200) {
                if (res.data.status === 301) {
                    Message.warning(res.data.message)
                    reject(res)
                    return;
                }
                let r = res.data
                sessionStorage.setItem("access_token", r.access_token)
                sessionStorage.setItem("refresh_token", r.refresh_token)
                sessionStorage.setItem("expires_in", r.expires_in)
                Message.success("登录成功！")
                resolve(res.data)
            }
        }).catch(res => {
            Message.error("登录失败，请检查网络！")
            reject(res)
        }).finally(res => {
            reject(res)
        })
    })
}

/**
 * GET解析参数
 */
function get(url, params) {
    for (let k in params) {
        if (!params[k] || params[k] === '' || params[k].length === 0) {
            delete params[k]
        }
    }
    return request({
        url: url,
        method: 'GET',
        params
    })
}

/**
 * 请求方法
 */
function post(url, data) {
    for (let k in data) {
        if (!data[k] || data[k] === '' || data[k].length === 0) {
            if (data[k] !== 0) {
                delete data[k]
            }
        }
    }
    return request({
        url: url,
        method: 'POST',
        data
    })
}

/**
 * PUT请求
 */
function put(url, data) {
    for (let k in data) {
        if (!data[k] || data[k] === '' || data[k].length === 0) {
            if (data[k] !== 0) {
                delete data[k]
            }
        }
    }
    return request({
        url: url,
        method: 'PUT',
        data
    })
}

function del(url, params) {
    for (let k in params) {
        if (!params[k] || params[k] === '' || params[k].length === 0) {
            delete params[k]
        }
    }
    return request({
        url: url,
        method: 'DELETE',
        params
    })
}

/**
 * 这个处理登录方法
 */
function request(obj) {
    let access_token = sessionStorage.getItem("access_token")
    if (access_token) {
        obj.headers = {
            'Cache-Control': 'no-cache',
            'Authorization': 'Bearer ' + sessionStorage.getItem("access_token")
        }
    }
    return normal(obj)
}


//正常请求
function normal(obj) {
    return new Promise((resolve, reject) => {
        service(obj).then(res => {
            if (res.status !== 200) {
                Message.error(res.data.message)
                if (res.data.status === 401) {
                    router.push('/login')
                }
            } else {
                resolve(res.data)
            }
        }).catch(res => {
            if (res.data) {
                Message.error(res.data.message)
            } else {
                Message.error("请求错误")
            }

            // router.push('/')
            reject(res)
        })
    })
}


//AES加密函数
function encryptAES(word, keyStr) {
    let key = cryptoJs.enc.Utf8.parse(keyStr);
    let srcs = cryptoJs.enc.Utf8.parse(word);
    let encrypted = cryptoJs.AES.encrypt(srcs, key, {
        mode: cryptoJs.mode.ECB,
        padding: cryptoJs.pad.Pkcs7
    });
    return encrypted.toString();
}

// AES解密函數
function decryptAES(word, keyStr) {
    let key = cryptoJs.enc.Utf8.parse(keyStr);
    let decrypt = cryptoJs.AES.decrypt(word, key, {
        mode: cryptoJs.mode.ECB,
        padding: cryptoJs.pad.Pkcs7
    });
    return cryptoJs.enc.Utf8.stringify(decrypt).toString();
}